home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / TPTUTR0F.ZIP / PASCAL5.TXT < prev    next >
Text File  |  1996-01-03  |  14KB  |  362 lines

  1.                    Turbo Pascal for DOS Beginning Tutorial
  2.                              by Glenn Grotzinger
  3.                 Part 5 -- Reading and Writing to Text Files.
  4.              All parts copyright 1995-96 (c) by Glenn Grotzinger
  5.  
  6.         Hello again.  I wanted to say the standard legal junk (didn't
  7. originally think of it).  This includes all parts, including parts
  8. previously released.  In using this tutorial, you hold Glenn Grotzinger
  9. responsible for nothing you may do or that may happen to your machine as
  10. a result of you trying out code, or writing code as a result of this
  11. tutorial.  All distribution is to be approved by Glenn Grotzinger in
  12. advance.  I give permission for free usage and distribution of these
  13. parts as posted in comp.lang.pascal.borland for use by private
  14. individuals in learning Pascal as long as all copyright notices and
  15. author (written by) references are kept intact, and no text is changed
  16. ANYWHERE.  The exception to the previous statement is the Microsoft
  17. Network, to which NONE of these parts may be legally distributed to.
  18. Commercial usage of this material in any way is subject to
  19. my approval and possible compensation to me (You sell my work, I want a
  20. cut in it).  Plagarism is INTOLERABLE, and I WILL NOT BE KIND TO ANY
  21. INSTANCES OF PLAGARISM. Please give me credit for anything you use
  22. directly out of these tutorials. A whole formatted version will be
  23. available when all of the parts are written.
  24.  
  25. program part4; uses crt;
  26.  
  27.   { This program offers a menu-type system in order to convert a number
  28.     of seconds to hours, minutes, and seconds; and to convert a military
  29.     time to AM/PM time }
  30.  
  31.   var
  32.     choice: integer;
  33.  
  34.   procedure showmenu;
  35.     { This procedure shows the main menu. }
  36.     begin
  37.       writeln('1. Convert a number of seconds to hours, minutes, and',
  38.               ' seconds.');
  39.       writeln('2. Convert a given military time to AM/PM time.');
  40.       writeln('3. Quit the program.');
  41.       writeln;
  42.       writeln('Please enter a choice:');
  43.     end;
  44.  
  45.   procedure convseconds;
  46.      var
  47.        totalseconds: integer;
  48.        hours, minutes, seconds: integer;
  49.        temp: integer;
  50.      begin
  51.        clrscr;
  52.        write('Enter a total number of seconds: ');
  53.        readln(totalseconds);
  54.        writeln;
  55.        temp := totalseconds div 60;
  56.        seconds := totalseconds mod 60;
  57.        hours := temp div 60;
  58.        minutes := temp mod 60;
  59.        writeln;
  60.        writeln(totalseconds, ' seconds is ', hours, ' hours, ', minutes,
  61.               ' minutes, ', seconds, ' seconds.');
  62.        writeln;
  63.        writeln('Press ENTER to continue:');
  64.        readln;
  65.      end;
  66.  
  67.   procedure convmilitary;
  68.     { Version 1.1.  Bug found and e-mailed to me.  It is appreciated. }
  69.     { Involved the reporting of times from 0000 to 0059...Looks to }
  70.     { be fixed now. (wrote this in a very dazed state -- post-surgery)}
  71.  
  72.     var
  73.       hours, minutes: integer;
  74.       meridian: char;
  75.     begin
  76.       clrscr;
  77.       write('Enter a military time''s hours: ');
  78.       readln(hours);
  79.       write('Enter a military time''s minutes: ');
  80.       readln(minutes);
  81.       if hours >= 12 then
  82.         begin
  83.           meridian := 'P';
  84.           hours := hours - 12;
  85.         end
  86.       else
  87.         meridian := 'A';
  88.       if hours = 0 then
  89.          hours := 12;
  90.       writeln;
  91.       write('It is ');
  92.       write(hours);
  93.       write(':');
  94.       if minutes < 10 then
  95.         write('0');
  96.       write(minutes);
  97.       writeln(' ', meridian, 'M.');
  98.       writeln;
  99.       writeln('Press ENTER to continue:');
  100.       readln;
  101.     end;
  102.  
  103.   begin
  104.     choice := 10;
  105.     while choice <> 3 do
  106.       begin
  107.         clrscr;
  108.         showmenu;
  109.         readln(choice);
  110.         case choice of
  111.           1: convseconds;
  112.           2: convmilitary;
  113.         end;
  114.       end;
  115.   end.
  116. OK.  On to new stuff...
  117.  
  118. Addressing Files
  119. ================
  120. To address a file, we use the assign statement.  We use a text variable to
  121. refer to the file, and a string to refer to the actual pathname and filename
  122. of the file.
  123.  
  124. To open a file, we use a reset(<file variable>); statement to read it.
  125.  
  126. To write a new file, we use a rewrite(<file variable>); statement.
  127.  
  128. To close a file after we are done accessing it for read or write, we use
  129. the close(<filevar>).
  130.  
  131. Special Identifiers
  132. ===================
  133. There are functions defined in standard Pascal which aid us in processing
  134. text files.  They are eof(<filevar>) and eoln(<filevar>).  They return
  135. boolean values.  They are signals we can use in loops to aid us in finding
  136. our way in text files.  EOF signals when we are at the end of a file.
  137. EOLN signals when we are at the end of a line of text in a file.
  138.  
  139. NOTE: Keep in mind, we can have as many files defined as we need.  The only
  140. limitation is that we can only have a maximum of the number of files defined
  141. in the FILES= statement of the config.sys of the particular machine we are
  142. on open at any one time.  It is always prudent to close files after you are
  143. done with them.
  144.  
  145.  
  146. Text file concepts and reading/writing to text files
  147. ====================================================
  148. A sample program to illustrate all the items above.  We will be doing a
  149. character by character read on an input file named DATA.TXT using eoln
  150. and eof properly, and uppercasing the output of the file using the
  151. standard upcase function. The output will be written to another output file
  152. named UPCASED.TXT.
  153.  
  154. program tutorial15;
  155.   var
  156.     infile, outfile: text;
  157.     inputchar: char;
  158.   begin
  159.     assign(infile, 'DATA.TXT'); { associate var infile with DATA.TXT }
  160.     reset(infile); { open DATA.TXT for read }
  161.     assign(outfile, 'UPCASED.TXT'); { assoc. var outfile with UPCASED.TXT }
  162.     rewrite(outfile); { open UPCASED.TXT for write }
  163.     while not eof(infile) do { while we're not at the EOF for infile }
  164.       begin
  165.         while not eoln(infile) do { while not EOLN for infile }
  166.           begin
  167.             read(infile, inputchar);
  168.             write(outfile, upcase(inputchar)); { process and output }
  169.           end;
  170.         writeln(outfile);  { when end of line, advance both files down }
  171.         readln(infile);    { one line }
  172.       end;
  173.     close(infile);     { we're done with both of these files.  Close 'em }
  174.     close(outfile);    { time. }
  175.   end.
  176.  
  177. This program is primarily for illustration purposes of all the new concepts
  178. we need to know in order to access files (there is a lot better way out
  179. there of doing it).  As long as we remember what exactly is read and
  180. considered as each type of variable (integer, char, string[limit], etc,
  181. etc), we can read all sorts of data from a text file and write data back
  182. out to a text file.  To illustrate:  If we have the following input file
  183. as on disk...
  184.  
  185. 14 23 34 53 32 Glenn Grotzinger
  186. 23 23 12 33 23 Clinton Sucks!
  187.  
  188. If we perform ONE read from a varied amount of different types from the
  189. first position of the first line, we will see the following:
  190.  
  191.  CHARread: 1
  192.  INTEGERread: 14
  193.  STRING[20]read: 14 23 34 53 32 Glenn
  194.  STRINGread: 14 23 34 53 32 Glenn Grotzinger
  195.  
  196. readln/writeln goes to the next line, whichever references what we are doing
  197. to the text file.
  198.  
  199. We must keep these general rules in mind (I hope you played around with the
  200. read and write commands a lot, that playing will help you A LOT!).
  201.  
  202. Another illustration to see usage of files.  It's the BETTER rewrite of
  203. tutorial15.  We must also keep in mind that to read a text file, EOLN
  204. is not necessarily required, but EOF is ALWAYS REQUIRED.  Improvements:
  205. We can use a string and write a function to uppercase the whole string.
  206. Plus, there's one little logic error above...Figure out why I do the
  207. reads and writes different below and you'll have mastered the idea of
  208. reading/writing files...(I intended to just demo the commands earlier,
  209. this is a demo of how they should be used logically...)
  210.  
  211. program tutorial16;
  212.  
  213.   var
  214.     inputstring: string;
  215.     infile, outfile: string;
  216.  
  217.   function upstr(instring: string):string;
  218.     { This function uppercases a whole string }
  219.     var
  220.       i: integer;
  221.       newstr: string;
  222.     begin
  223.       newstr := '';
  224.       for i := 1 to length(instring) do
  225.         newstr := newstr + upcase(instring[i]);
  226.       { we can piece strings together using +.  Keep it in mind }
  227.     end;
  228.  
  229.    begin
  230.      assign(infile, 'DATA.TXT');
  231.      reset(infile);
  232.      assign(outfile, 'UPCASED.TXT');
  233.      rewrite(outfile);
  234.      readln(infile, inputstring);
  235.      while not eof(infile) do
  236.        begin
  237.          writeln(outfile, upstr(inputstring));
  238.          readln(infile, inputstring);
  239.        end;
  240.      writeln(outfile, upstr(inputstring));
  241.      close(infile);
  242.      close(outfile);
  243.    end.
  244.  
  245. Remember to play with the logic in accessing text files.  And in reading and
  246. writing files, BE SURE YOU USE FILES THAT YOU CAN STAND TO LOSE IF YOU ARE
  247. NOT COMPLETELY COMFORTABLE WITH PROGRAMMING FOR FILE ACCESS.  IF A FILE
  248. BY A NAME YOU USE FOR A PROGRAM ALREADY EXISTS ON THE DRIVE, AND YOU REWRITE
  249. IT, IT WILL BE COMPLETELY LOST!  THIS MEANS ANY UNDELETE PROGRAM WILL *NOT*
  250. BE ABLE TO RECOVER THE FILE!!!!!!!!!!!   I will cover in a later part
  251. how to find out whether files exist on the drive as well as other commands
  252. and functions used in Pascal to perform DOS-like functions (delete files,
  253. make directories, remove directories, and so forth).
  254.  
  255. Printer Output
  256. ==============
  257.         The printer can basically be treated as a write-only file (you only
  258. rewrite it, not reset it).  To use the printer?  Use the unit printer, like
  259. you did the unit crt or wincrt before then write to a text file variable
  260. named lst....Printer defines everything you need to write to the printer.
  261. Printer assumes LPT1, so if your printer is on something else, you can
  262. define the text file variable to be the port address for the printer....
  263.  
  264. program tutorial17; uses printer;
  265.   var
  266.     str: string;
  267.     infile: text;
  268.   begin
  269.     assign(infile, 'PRINTME.TXT');
  270.     reset(infile);
  271.     readln(infile, str);
  272.     while not eof(infile) do
  273.       begin
  274.         writeln(lst, str);
  275.         readln(infile, str);
  276.       end;
  277.     writeln(lst, str);
  278.     writeln('File sent to printer on LPT1..');
  279.   end.
  280.  
  281.  
  282. Practice Programming Problem Notes
  283. ==================================
  284.         Probably ALL programs I pose on these in the future will involve
  285. at least ONE data file off of disk.  If it is a binary one that I have
  286. created for express purpose of these problems, I will be attaching it to
  287. the tutorial message as a binary file attachment.  If its a text file,
  288. I will probably ask you to create it, giving you the format.  If you have
  289. been doing source code, you should be able to use a text file editor.
  290.  
  291. Practice Programming Problem #5
  292. ===============================
  293.         Write a program in Pascal and entirely Pascal which will conduct
  294. a worker-pay recording.  Be sure the program is modular and uses functions
  295. and procedures to the best benefit, as well as efficiently coded (be sure
  296. you are using format codes!).  We will be reading worker names and data
  297. from a file in the current directory with the program named WORKER.TXT.
  298. Format of input and output files will be covered later.  What we will be
  299. doing is figuring out how much to pay each of these employees in our data
  300. file.  Points to keep in mind:
  301.  
  302.    1) Gross pay is hourly rate * hours-worked for hours worked below 40.
  303.    2) 40 hours of time is full-time pay, beyond 40 hours is time and a half.
  304.       Therefore, we must pay them 1/2 more than we normally would at the
  305.       hourly computed rate for any hours above 40 from point 1.
  306.    3) Income Taxes are 15% of computed gross pay (before taxes, etc).
  307.    4) We must indicate all of these deductions by computations in the output.
  308.    5) We may have 1 employee, we may have 10,000.  We need to give the
  309.       user some indication as to what we are doing (all we will see is
  310.       a blank prompt otherwise.) so they won't think our program has hung
  311.       or crashed.  Write a message such as "Processing <employee name>" to
  312.       the screen for each employee.
  313.  
  314. Write a report of what our deductions are from each person's salary, and
  315. what we are paying each employee to a file named PAYOUT.TXT.
  316.  
  317. Format of WORKER.TXT (I recommend you type this in *EXACTLY* and use it)
  318. --------------------
  319. Glenn Grotzinger    44.25  7.34
  320. Joe Schmoe          65.32  4.35
  321. Jim Nabors          40.00  10.01
  322. Sheila Roberts      32.12  6.25
  323. Kathy York          23.21  11.10
  324. --------------------
  325.  
  326. (the area between all the --- is the WORKER.TXT to use.... -- another note:
  327. be sure there aren't any blank lines at the bottom of the file -- those
  328. cause problems...)
  329. First thing on each line is employee name (max of 20 chars).
  330. Second thing is total hours worked.
  331. Third thing is pay rate.
  332.  
  333. Format of PAYOUT.TXT
  334. --------------------
  335.                       The International Widget, Inc.
  336.                        PayOut And Deductions Sheet
  337.  
  338. Employee              Hours  Rate  GrossPay  Overtime  IncomeTax  NetPay
  339. ========================================================================
  340. Glenn Grotzinger      34.25  7.34   345.23     32.34     15.34    305.23
  341. ...
  342.  
  343.  
  344. --------------------
  345. (The numbers should be correct, and the file should appear sort of like
  346. this, but with more entries (equivalent to the number of entries in the
  347. WORKER.TXT file.  This is only a sample illustration.)
  348.  
  349. Note:  In any program, you should always make accounts for changes in the
  350. number of lines of text in an input file.  Use EOF.  Do not use a
  351. defined set loop.  Also, as a tip, to get the output the way you want it
  352. to look, it doesn't hurt to type it out as a sample, so you know how to
  353. space it when you go into the programming part of it.
  354.  
  355. Next Time
  356. =========
  357. We will discuss arrays and their usage.  If there is a difficulty in inter-
  358. preting data files for text files, tell me, and I will probably attach them
  359. as binaries in the future.  Please send all comments, inquiries, etc, etc
  360. to ggrotz@2sprint.net.  P.S.  Sorry this one ain't too fun...Couldn't think
  361. of anything better to get you the practice in using text files...
  362.